package com.stephen.demo.config;

import com.stephen.demo.shiro.cache.RedisCacheManager;
import com.stephen.demo.shiro.realms.CustomizeRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by stephen on 2021-04-05 11:53 .
 * Description: shiro配置
 */
@Configuration
public class ShiroConfig {

    // 创建ShiroFilter
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 配置系统公共资源和受限资源
        Map<String,String> map = new HashMap<String, String>();
        // 公共资源路径,anno表示不用认证,可匿名访问
        // 不需要添加上下文路径
        map.put("/user/login","anon");
        map.put("/user/register","anon");
        map.put("/register.jsp","anon");
        map.put("/user/getImage","anon"); // 放行验证码
        // 需要认证的资源
        map.put("/**","authc"); // authc表示这个请求需要认证和授权
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //
        // 设置默认认证界面路径,默认就是login.jsp
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        return shiroFilterFactoryBean;
    }

    // 创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    // 自定义Realm
    @Bean
    public Realm realm() {
        CustomizeRealm customizeRealm = new CustomizeRealm();
        // 指定加密算法和hash次数
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);
        customizeRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        // 开启缓存管理
        customizeRealm.setCacheManager(new RedisCacheManager());
        // 开启全局缓存
        customizeRealm.setCachingEnabled(true);
        // 开启认证缓存
        customizeRealm.setAuthenticationCachingEnabled(true);
        // 自定义认证缓存名称
        customizeRealm.setAuthenticationCacheName("authenticationCache");
        // 开启授权缓存
        customizeRealm.setAuthorizationCachingEnabled(true);
        // 自定义授权缓存名称
        customizeRealm.setAuthorizationCacheName("authorizationCache");
        return customizeRealm;
    }

}
